# Copyright 2015 ZhangZhaoyuan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require 'aliyunsdk/core/utils/api_util'
require 'aliyunsdk/core/errors'
require 'net/http'
require 'uri'
module Aliyunsdk
  module Core
    class HttpRequest

      # Constructor
      # @param http_method [String]
      # @param url [String]
      # @param data [String]
      # @param headers [Hash]
      def initialize(acs_request, domain, **headers)
        @http_method =acs_request.http_method
        @headers = headers
        @url = "#{acs_request.http_protocol}://#{domain}"
        @acs_req = acs_request
      end

      # Send Request to Server
      # @return [String] Response
      def get_response()
        uri = URI "#{@url}?#{@acs_req.generate_url_params}"
        case @http_method
          when ApiUtil::HTTP_GET_METHOD
            request = Net::HTTP::Get.new uri
          when ApiUtil::HTTP_POST_METHOD
            request = Net::HTTP::Post.new uri
          else
            raise ClientException, "Unknown http method(#{@http_method})"
        end

        # set headers
        @headers.each_pair do |k, v|
          request[k] = v
        end

        Net::HTTP.start(uri.host, uri.port,
                        use_ssl: uri.scheme.eql?(ApiUtil::PROTOCOL_HTTPS),
                        open_timeout: 30, read_timeout: 30, ssl_timeout: 30) { |http|
          http.request request
        }
      end
    end
  end
end